package com.njrsrc.android.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.njrsrc.R;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.android.tasks.LoginTask;
import com.njrsrc.android.tasks.RegisterTask;
import com.njrsrc.android.tasks.UploadPicTask;
import com.njrsrc.android.views.CameraPreview;
import com.njrsrc.android.views.TitleBar;
import com.njrsrc.common.url.FileDirProvider;
import com.njrsrc.common.url.RequestUrlProvider;
import com.njrsrc.common.utils.Base64;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

/**
 * 注册页面
 * 
 * @author Administrator
 * 
 */
public class RegisterActivity extends BaseActivity implements OnClickListener {
	protected static final String TAG = "RegisterActivity";
	private TitleBar mBar;
	private LinearLayout usernameLayout, passwordLayout;
	private EditText usernameEditText, passwordEditText,confirmPassword;
	/** 游客、注册按钮 */
	private ImageView visitorImageView, loginImageView;
	private Button registerButton;
	private UserInfo registerInfo;
	private ProgressDialog progressDialog;
	private Camera mCamera;
	private CameraPreview mPreview;
	/** 拍照按钮 */
	private ImageView takePicture;
	public static final int MEDIA_TYPE_IMAGE = 1;
	/** 有前置摄像头 */
	private boolean hasFrontCamera;
	private boolean canTaking = false;
	private String picPath;
	private UserInfo loginInfo;
	public static final int CAMERA  = 0x01;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			
			case MsgID.LOGIN_ERROR:
				// 登录失败
				Helpers.closeProgressDialog(progressDialog);
				Helpers.showToast(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT);
				break;
			case MsgID.LOGIN_FAIL:
				// 登录失败
				Helpers.closeProgressDialog(progressDialog);
				Helpers.showToast(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT);
				break;

			case MsgID.LOGIN_SUCCESS:
				// 登录成功
				AppApplication.mUserID = loginInfo.getUser_id();
				AppApplication.mToken = loginInfo.getToken();
				AppApplication.mResumeID = loginInfo.getResume_id();
				AppApplication.mUserName = loginInfo.getLogin_name();
				AppApplication.hrLetterCount = "0";
				AppApplication.isLogin = true;
				// 将用户名密码保存到SharedPreferences中,下次自动登录
				Editor editor = preferences.edit();
				editor.putString("user", loginInfo.getLogin_name());
				editor.putString("password", loginInfo.getPassword());
				editor.commit();
				// 注册成功后上传头像
				if(picPath != null && picPath.trim().length() != 0)
				{
					Map<String, String> params = new HashMap<String, String>();
					params.put("token", AppApplication.mToken);
					params.put("user_id", AppApplication.mUserID);
					params.put("pic", picPath);
					String url = RequestUrlProvider.USER_UPLOAD_PIC;
					Object[] args = new Object[4];
					args[0] = mHandler;
					args[1] = url;
					args[2] = loginInfo;
					args[3] = params;
					Helpers.showToast(RegisterActivity.this, "正在上传头像", Toast.LENGTH_SHORT);
					new UploadPicTask().execute(args);
				}else
				{
					Intent mainIntent = new Intent();
					mainIntent.setClass(RegisterActivity.this, MainActivity.class);
					mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(mainIntent);
				}
				break;
			case -2:
				// 注册失败
				Helpers.closeProgressDialog(progressDialog);
				Helpers.showToast(RegisterActivity.this, registerInfo.getError_message(), Toast.LENGTH_SHORT);
				break;

			case 0:
				// 注册成功
				Helpers.showToast(RegisterActivity.this, R.string.registSuc, Toast.LENGTH_SHORT);
				AppApplication.mUserID = registerInfo.getUser_id();
				AppApplication.mToken = registerInfo.getToken();
				
				String username = usernameEditText.getText().toString();
				String password = passwordEditText.getText().toString();
				// Base64加密
				password = Base64.encode(password.getBytes());
				// 发送登录请求
				List<String> loginParams = new ArrayList<String>();
				loginParams.add(username);
				loginParams.add(password);
				String loginUrl = Helpers.combinaStr(RequestUrlProvider.USER_LOGIN, loginParams);
				loginInfo = new UserInfo();
				loginInfo.setLogin_name(username);
				loginInfo.setPassword(password);
				Object[] loginArgs = new Object[3];
				loginArgs[0] = mHandler;
				loginArgs[1] = loginUrl;
				loginArgs[2] = loginInfo;
				new LoginTask().execute(loginArgs);
				break;
			case 6:
				// 头像上传成功
				Helpers.closeProgressDialog(progressDialog);
				Helpers.showToast(RegisterActivity.this, "头像上传成功", Toast.LENGTH_SHORT);
				AppApplication.mHeadUrl = loginInfo.getPic_url();
				Intent mainIntent = new Intent();
				mainIntent.setClass(RegisterActivity.this, MainActivity.class);
				mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mainIntent);
				break;
			case 7:
				// 头像上传失败
				Helpers.closeProgressDialog(progressDialog);
				Helpers.showToast(RegisterActivity.this, "头像上传失败", Toast.LENGTH_SHORT);
				finish();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 拍照回调
	 */
	private PictureCallback mPicture = new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				Log.d(TAG, "Error creating media file, check storage permissions");
				return;
			}
			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
				picPath = pictureFile.getAbsolutePath();
				Log.d(TAG, "the picture you have taken is now on location : " + picPath);
			} catch (FileNotFoundException e) {
				Log.d(TAG, "File not found: " + e.getMessage());
			} catch (IOException e) {
				Log.d(TAG, "Error accessing file: " + e.getMessage());
			}
		}
	};

	/** Create a File for saving an image or video */
	private File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.
		// 返回/data/data/youPackageName/files的File对象
		File mediaStorageDir = new File(this.getFilesDir(), "head");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(TAG, "failed to create directory");
				return null;
			}
		}
		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
		} else {
			return null;
		}

		return mediaFile;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		hasFrontCamera = checkCameraHardware(RegisterActivity.this);
		initView();
	}

	private void initCamera() {
		// Create an instance of Camera
		mCamera = getCameraInstance();
		// Create our Preview view and set it as the content of our activity.
		mPreview = new CameraPreview(this, mCamera);
		mPreview.setBackgroundColor(Color.TRANSPARENT);
		FrameLayout preview = (FrameLayout) findViewById(R.id.show_pic_area);
		preview.addView(mPreview);
		canTaking = true;
	}

	private void initView() {
		mBar = (TitleBar) findViewById(R.id.activity_title_bar);
        mBar.setTitleText("注册");
        mBar.back.setOnClickListener(this);
		visitorImageView = (ImageView) findViewById(R.id.login_visitor_img);
		loginImageView = (ImageView) findViewById(R.id.login_login_img);
		usernameLayout = (LinearLayout) findViewById(R.id.layout_username);
		passwordLayout = (LinearLayout) findViewById(R.id.layout_password);
		usernameEditText = (EditText) findViewById(R.id.login_edit_username);
		passwordEditText = (EditText) findViewById(R.id.login_edit_password);
		confirmPassword = (EditText) findViewById(R.id.confirm_edit_password);
		registerButton = (Button) findViewById(R.id.reg_btn_reg);
		takePicture = (ImageView) findViewById(R.id.take_picture);
		visitorImageView.setOnClickListener(this);
		loginImageView.setOnClickListener(this);
		usernameLayout.setOnClickListener(this);
		passwordLayout.setOnClickListener(this);
		registerButton.setOnClickListener(this);
		takePicture.setOnClickListener(this);
	}

	/** Check if this device has a camera */
	private boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			// 需要继续检查是否有前置摄像头
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	/** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open(); // attempt to get a Camera instance
		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
			e.printStackTrace();
		}
		return c; // returns null if camera is unavailable
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tb_ibtn_back:
//			surfaceDestroyed();
			finish();
			break;
		case R.id.layout_username:
			// 用户名输入点击区域
			usernameEditText.requestFocus();
			Helpers.showSoftKeyboard(RegisterActivity.this, usernameEditText);
			break;
		case R.id.layout_password:
			// 密码输入点击区域
			passwordEditText.requestFocus();
			Helpers.showSoftKeyboard(RegisterActivity.this, passwordEditText);
			break;
		case R.id.confirm_edit_password:
			// 密码输入点击区域
			confirmPassword.requestFocus();
			Helpers.showSoftKeyboard(RegisterActivity.this, confirmPassword);
			break;
		case R.id.login_visitor_img:
			// 逛逛按钮
			onKeyDown(KeyEvent.KEYCODE_BACK, null);
			break;

		case R.id.login_login_img:
			// 动画
			Animation loginBtnAnimation = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.login_btn_translate);
			Animation registerBtnAnimation = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.register_btn_translate);
			loginImageView.startAnimation(loginBtnAnimation);
			registerButton.startAnimation(registerBtnAnimation);
			// 登录按钮
			mCamera.release();
			final Intent loginIntent = new Intent();
			loginIntent.setClass(RegisterActivity.this, LoginActivity.class);
			TimerTask task = new TimerTask() {
				
				@Override
				public void run() {
					startActivity(loginIntent);
					finish();
				}
			};
			new Timer().schedule(task, 300);
			break;

		case R.id.reg_btn_reg:
			// 点击注册
			String username = usernameEditText.getText().toString();
			String password = passwordEditText.getText().toString();
			String confirmPwd = confirmPassword.getText().toString();
			if (TextUtils.isEmpty(username)) {
				Helpers.showToast(RegisterActivity.this, R.string.registerUserInputTip, Toast.LENGTH_SHORT);
				return;
			}
			if (TextUtils.isEmpty(password)) {
				Helpers.showToast(RegisterActivity.this, R.string.registerPassInputTip, Toast.LENGTH_SHORT);
				return;
			}
			if (TextUtils.isEmpty(confirmPwd)) {
				Helpers.showToast(RegisterActivity.this, R.string.registerPassInputTipAgain, Toast.LENGTH_SHORT);
				return;
			}
			
			if(!password.equals(confirmPwd))
			{
				Helpers.showToast(RegisterActivity.this, R.string.pwdnotsame, Toast.LENGTH_SHORT);
				return;
			}
			// Base64加密
			password = Base64.encode(password.getBytes());
			// 发送登录请求
			Map<String, String> params = new HashMap<String, String>();
			params.put("login_name", username);
			params.put("password", password);
			params.put("email", username);
			String url = RequestUrlProvider.USER_REGISTER;
			registerInfo = new UserInfo();
			Object[] args = new Object[4];
			args[0] = mHandler;
			args[1] = url;
			args[2] = registerInfo;
			args[3] = params;
			progressDialog = Helpers.showProgressDialog(RegisterActivity.this, R.string.registing);
			// 注册
			new RegisterTask().execute(args);

			break;

		case R.id.take_picture:
			if (!hasFrontCamera) {
				return;
			}
			
//			if(mCamera == null)
//			{
//				initCamera();
//			}else
//			{
//				if (canTaking) {
//					// get an image from the camera
//					mCamera.takePicture(null, null, mPicture);
//					canTaking = false;
//				} else {
//					// 准备重新拍照
//					mCamera.startPreview();
//					canTaking = true;
//				}
//			}
			
			Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(camera, CAMERA);
			
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			mCamera.release();
//			surfaceDestroyed();
			finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){
			   String sdState=Environment.getExternalStorageState();
			   String dstPath = "";
			   if(!sdState.equals(Environment.MEDIA_MOUNTED)){
				   File dir = context.getDir("files", Context.MODE_PRIVATE);
				   dstPath = dir.getAbsolutePath();
			   }else
			   {
				   File file = new File(FileDirProvider.icon);
				   if(!file.exists())
				   {
					   file.mkdirs();
				   }
				   dstPath = file.getPath();
			   }
			   new DateFormat();
			   String name= DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".png";
			   Bundle bundle = data.getExtras();
			   //获取相机返回的数据，并转换为图片格式
			   Bitmap bitmap = (Bitmap)bundle.get("data");
			   FileOutputStream fout = null;
			   picPath= dstPath+ File.separator + name;
			   try {
			    fout = new FileOutputStream(picPath);
			    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
			   } catch (FileNotFoundException e) {
			    e.printStackTrace();
			   }finally{
			    try {
			     fout.flush();
			     fout.close();
			    } catch (IOException e) {
			     e.printStackTrace();
			    }
			   }
			   //裁剪图片并显示
			   Bitmap showBitmap = Helpers.scaleBitmap(picPath, 150, 150);
			   ((FrameLayout) findViewById(R.id.show_pic_area)).setBackgroundDrawable(new BitmapDrawable(showBitmap));
		}
	}
	
	public void surfaceDestroyed() {
		mCamera.stopPreview();
		mCamera.release();
		mCamera = null;

	}
}